<template>
  <view class="app" :style="listHeightStyle">
    <u-navbar :title="title" @leftClick="leftClick" :autoBack="false" placeholder :border="false"
      :shadow="true"></u-navbar>
    <view class="title-view">
      <view class="text-title"> {{ formData.title }} </view>
      <view class="text-remark"> {{ formData.remark }} </view>
      <view class="text-current" v-if="formData.status == 1"> {{ formData.current_str }} </view>
      <view class="image" v-if="formData.status > 1">
        <image style="width: 145rpx;height: 130rpx;" v-if="formData.status == 2" src="@/static/apply/ytg.png"></image>
        <image style="width: 145rpx;height: 130rpx;" v-if="formData.status == 3" src="@/static/apply/yjj.png"></image>
        <image style="width: 145rpx;height: 130rpx;" v-if="formData.status == 4" src="@/static/apply/ycx.png"></image>
      </view>
    </view>

    <!-- 审批单详情内容 -->
    <view class="main-view">
      <view>
        <view class="main-title">所在部门</view>
        <view class="main-content"> {{ formData.deptName || '无' }} </view>
      </view>
      <view>
        <view class="main-title">审批编号</view>
        <view class="main-content"> {{ formData.formNo }} </view>
      </view>
      <view v-for="(item, index) in formData.detail" :key="index">

        <!-- {{ item.name }} -->
        <view class="main-title" style="position: relative;"
          v-if="(item.name !== 'QrCodePhotoUpload' && item.name !== 'Customized') || item.value?.length > 0 || hasScanPhoto(item)">
          <view v-if="item.name === 'QrCodePhotoUpload' && hasScanPhoto(item)" style="color: red;display: flex;">
            <view style="font-size: 40rpx;position: absolute;top: 16rpx;"> * </view>
            <view style="margin-left: 20rpx;">{{ item.label }}</view>
          </view>
          <view v-else>{{ item.label }}</view>
        </view>

        <view class="main-content"
          v-if="item.name === 'TextInput' || item.name === 'DateTime' || item.name === 'TextareaInput' || item.name === 'DeptPicker' || item.name === 'RolePicker' || item.name === 'DateTimeRange'">
          <pre style="white-space: pre-wrap;">{{ item.value }}</pre>
        </view>


        <view class="main-content" v-if="item.name === 'RichTextEditor'">
          <view v-html="item.value"></view>
        </view>


        <view class="main-content" v-if="item.name === 'SpanLayout' || item.name === 'SelectInput'">
          <template v-if="Array.isArray(item.value)">
            <view class="Mainvalue" v-for="(SpanLayout, index) in item.value" :key="index">
              <view class="main-title">
                {{ SpanLayout.label }}
              </view>
              <view>
                {{ SpanLayout.value || '无' }}
              </view>
            </view>
          </template>
          <template v-else>
            <view>{{ item.value }}</view>
          </template>
        </view>

        <view class="main-content" v-if="item.name === 'BasicData'">
          <template v-if="Array.isArray(item.value)">
            <view class="Mainvalue" v-for="(SpanLayout, index) in item.value" :key="index">
              <view class="main-title">
                {{ SpanLayout.label }}
              </view>
              <view>
                {{ SpanLayout.value || '无' }}
              </view>
            </view>
          </template>
          <template v-else>
            <view>{{ item.value }}</view>
          </template>
        </view>


        <view class="main-content" v-if="item.name === 'MultipleSelect'">
          {{ item.value }}
        </view>

        <view class="main-content" v-if="item.name === 'NumberInput'">
          {{ item.value }}
        </view>


        <view class="main-content" v-if="item.name === 'UserPicker'">
          {{ item.value }}
        </view>



        <view class="main-content" v-if="item.name === 'AmountInput'">
          {{ item.value || '--' }}
        </view>



        <view class="main-content" v-if="item.name === 'MapPicker'">
          {{ item.value }}
        </view>

        <view class="main-content" v-if="item.name === 'FileUpload'">
          <view v-if="item.value && item.value.length > 0">
            <view v-for="(file, index) in item.value" :key="index" class="file-item"
              @click="FileViewClick(item.value, file)">
              <text class="file-icon">{{ isImage(file.name) ? '🖼️' : '📄' }}</text>
              <text class="file-name" :title="file.name">{{ truncateMiddle(file.name) }}</text>
            </view>
          </view>
          <view v-else>无</view>
        </view>

        <view class="main-content"
          v-if="(item.name === 'ImageUpload') || (item.name === 'QrCodePhotoUpload' && (item.value?.length > 0 || hasScanPhoto(item)))">

          <!-- 已上传图片 -->
          <view v-if="item.value && item.value.length > 0" class="image-grid">
            <view v-for="(img, imgIndex) in item.value" :key="imgIndex" class="image-item"
              @click="ImgviewClick(item, img)">
              <image :src="ProcessingURL(img.url)" mode="aspectFill" class="uploaded-image"
                @error="handleImageError($event, img)" />
              <view v-if="img.error" class="alt-text">{{ img.altText || '图片加载失败' }}</view>
            </view>
          </view>

          <!-- 无已上传图片，显示扫码组件 -->
          <view v-else-if="item.name === 'QrCodePhotoUpload' && hasScanPhoto(item)">
            <QrCodePhotoUpload :formData="formData" :itemId="item.id"></QrCodePhotoUpload>
            <view></view>
          </view>

          <view v-else>无</view>
        </view>

        <view class="main-content" v-if="item.name === 'DocPicker'">
          <view v-if="item.value && item.value.length > 0">
            <view v-for="(DocPicker, index) in item.value" :key="index" class="DocPicker-item"
              @click="Relatedpopups(DocPicker)">
              <up-icon name="share-square" size="20" color="#999" class="doc-icon"></up-icon>
              <text class="doc-title"> {{ truncateMiddle(DocPicker.title) }} </text>
            </view>
          </view>
          <view v-else class="no-docs">无</view>
        </view>

        <view class="main-content table-container" v-if="item.name === 'TableList'">
          <scroll-view class="scroll-container" scroll-x="true">
            <table>
              <thead>
                <tr>
                  <!-- 如果有 head 就直接用 head -->
                  <th
                    v-for="(head, i) in (item.head && item.head.length ? item.head : (item.value[0] || []).map(col => col.label))"
                    :key="i">
                    {{ head }}
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(list, k) in item.value" :key="k">
                  <td v-for="(row, j) in list" :key="j" class="nowrap">
                    <!-- 如果是对象，显示 row.value，否则直接显示 row -->
                    <span v-if="row && typeof row === 'object'">{{ row.value }}</span>
                    <span v-else>{{ row }}</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </scroll-view>
        </view>

        <view class="main-content table-container" v-if="item.name === 'Customized'">
          <view class="main-content">
            <view class="main-title">
              日期
            </view>
            {{ item?.value?.afterSaleDate || item?.value?.date }}
          </view>

          <view style="margin-top: 10px;margin-bottom: 10px" class="main-content"
            v-if="item.value?.products?.length > 0">
            <view class="main-title">
              所属部门
            </view>
            {{ item?.value?.department }}
          </view>


          <view style="margin-top: 10px;margin-bottom: 10px" class="main-content"
            v-if="item.value?.products?.length > 0">
            <view class="main-title">
              销售人员
            </view>
            {{ item?.value?.salesPerson }}
          </view>


          <view v-if="item.value?.orderList?.length > 0">
            <view style="margin-bottom: 8px" class="main-content main-title">
              订单-客户信息
            </view>
            <!-- 滚动容器 -->
            <scroll-view class="scroll-container" scroll-x="true">
              <table>
                <thead>
                  <tr>
                    <th v-for="(table, i) in orderList" :key="i">
                      {{ table.title }} </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(row, rowIndex) in item.value.orderList" :key="rowIndex">
                    <td v-for="(header, colIndex) in orderList" :key="colIndex" class="nowrap"
                      :class="{ highlight: header.field === 'orderNum' }">
                      {{ row[header.field] }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </scroll-view>
          </view>

          <view v-if="item.value?.productList?.length > 0">
            <view style="margin-bottom: 8px" class="main-content main-title">
              产品信息
            </view>
            <!-- 滚动容器 -->
            <scroll-view class="scroll-container" scroll-x="true">
              <table>
                <thead>
                  <tr>
                    <th v-for="(table, i) in productList" :key="i">
                      {{ table.title }} </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(row, rowIndex) in item.value.productList" :key="rowIndex">
                    <td v-for="(header, colIndex) in productList" :key="colIndex" class="nowrap"
                      :class="{ highlight: header.field === 'orderNum' }">
                      {{ row[header.field] }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </scroll-view>
          </view>

          <view v-if="item.value?.products?.length > 0">
            <view style="margin-bottom: 8px" class="main-content main-title">
              订单客户信息
            </view>
            <scroll-view class="scroll-container" scroll-x="true">
              <table>
                <thead>
                  <tr>
                    <th v-for="(table, i) in products" :key="i">
                      {{ table.title }} </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(row, rowIndex) in item.value.products" :key="rowIndex">
                    <td v-for="(header, colIndex) in products" :key="colIndex" class="nowrap"
                      :class="{ highlight: header.field === 'orderNum' }">
                      {{ row[header.field] }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </scroll-view>
          </view>

          <view v-if="item.value?.customerList?.length > 0">
            <view style="margin-bottom: 8px" class="main-content main-title">
              订单客户信息
            </view>
            <scroll-view class="scroll-container" scroll-x="true">
              <table>
                <thead>
                  <tr>
                    <th v-for="(table, i) in customerList" :key="i">
                      {{ table.title }} </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(row, rowIndex) in item.value.customerList" :key="rowIndex">
                    <td v-for="(header, colIndex) in customerList" :key="colIndex" class="nowrap"
                      :class="{ highlight: header.field === 'orderNum' }">
                      {{ row[header.field] }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </scroll-view>
          </view>

          <view v-if="item.value?.orderCustomer?.length > 0">
            <view style="margin-bottom: 18px" class="main-content main-title">
              要更正的客户信息
            </view>
            <scroll-view class="scroll-container" scroll-x="true">
              <table>
                <thead>
                  <tr>
                    <th v-for="(table, i) in orderCustomer" :key="i">
                      {{ table.title }} </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(row, rowIndex) in item.value.orderCustomer" :key="rowIndex">
                    <td v-for="(header, colIndex) in orderCustomer" :key="colIndex" class="nowrap"
                      :class="{ highlight: header.field === 'orderNum' }">
                      {{ row[header.field] }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </scroll-view>
          </view>

          <view style="margin-bottom: 8px" class="main-content main-title" v-if="item.value?.products?.length > 0">
            <view class="main-title">
              调价原因
            </view>
            {{ item?.value?.reason }}
          </view>
        </view>
      </view>
    </view>

    <!-- 审批流程 -->
    <view class="process-container">
      <view class="process-title">审批流程</view>

      <view class="timeline">
        <view v-for="(item, index) in formData.process" :key="index" class="timeline-item">
          <!-- 时间线节点 -->
          <view class="timeline-node">
            <view class="node-icon" :class="{ 'read': item.ptype === 3 && item.content.some(i => i.read === 2) }">
              <!-- 头像/图标 -->
              <template v-if="item.ptype !== 3">
                <view @click="viewUserInfo(item)">
                  <up-image v-if="item.avatar" :src="item.avatar" :show-loading="true" width="40px" height="40px"
                    radius="4px"></up-image>
                  <up-avatar v-else size="40" shape="square" bg-color="#409eff">
                    <text class="avatar-text">{{ item.name.slice(-2) }}</text>
                  </up-avatar>
                </view>
              </template>

              <!-- 抄送图标 -->
              <template v-else>
                <view class="cc-icon">
                  <up-icon name="volume" color="#ffffff" size="18"></up-icon>
                </view>
              </template>

            </view>

            <!-- 时间线连接线 -->
            <view v-if="index !== formData.process.length - 1" class="timeline-connector"></view>
          </view>

          <!-- 流程内容 -->
          <view class="process-content"
            :class="index < formData.process.length - 1 ? (formData.process[index + 1]?.vr ? 'lines' : 'line') : ''">
            <!-- 头部信息 -->
            <view class="process-header">
              <view class="process-title-text">{{ item.title }}</view>
              <view class="process-time">{{ item.date }}</view>
            </view>

            <!-- 操作人信息 -->
            <view class="process-user">
              {{ item.name }}
              <text v-if="item.ptype === 2 || item.ptype === 5" class="process-type">
                {{ item.type_name }}
              </text>
            </view>

            <!-- 审批意见 -->
            <view v-if="item.content && item.ptype !== 3 && item.ptype !== 4" class="process-comment">
              {{ item.content }}
            </view>

            <view v-if="item.ptype === 4" class="process-comment">
              <!-- 文字内容 -->
              <view v-if="item.content" class="comment-content">
                <view v-html="item.content"></view>
              </view>

              <!-- 撤回按钮 -->
              <view class="withdraw" v-show="item?.power" @click="Withdrawalevent(item.cancel_id)">撤回</view>

              <view v-if="item.ptype == 4" class="process-attachments">
                <!-- 图片预览 -->
                <view v-if="item.img?.length > 0" class="attachment-images">
                  <view class="image-grid">
                    <view v-for="img in item.img" :key="img.id" class="image-item" @click="ImgviewClick(item.img, img)">
                      <image :src="`${COMMON_API_BASE_URL}${img.path}`" mode="aspectFill"
                        @error="handleImageError($event, img)" class="image-preview"></image>
                      <text v-if="img.error" class="image-alt">
                        {{ '图片加载失败' }}
                      </text>
                    </view>
                  </view>
                </view>

                <!-- 文件预览 -->
                <view v-if="item.file?.length > 0" class="attachment-files">
                  <view v-for="file in item.file" :key="file.id" class="file-preview"
                    @click="FileViewClick(item.file, file)">
                    <text class="file-icon">{{ isImage(file.filename) ? '🖼️' : '📄' }}</text>
                    <text class="file-name" :title="file.filename">{{ truncateMiddle(file.filename) }}</text>
                  </view>
                </view>
              </view>
            </view>

            <!-- 抄送人员 -->
            <view v-if="item.ptype === 3" class="cc-users">
              <view class="cc-users-list">
                <view v-for="(user, uIndex) in item.content.slice(0, 3)" :key="uIndex" class="cc-user"
                  @click="viewUserInfo(user)">
                  <view class="cc-user-avatar">
                    <up-avatar v-if="user.avatar" :src="user.avatar" size="36" shape="square"
                      bg-color="#409eff"></up-avatar>
                    <up-avatar v-else size="36" shape="square" bg-color="#409eff">
                      <text class="avatar-text">{{ user.name.slice(-2) }}</text>
                    </up-avatar>
                    <view v-if="user.read === 2" class="read-badge"></view>
                  </view>
                  <text class="cc-user-name">{{ user.name }}</text>
                </view>

                <!-- 更多按钮 -->
                <view v-if="item.content.length > 3" class="cc-more" @click="showMorePeople(item)">
                  <view class="cc-more-icon">
                    <text>+{{ item.content.length - 3 }}</text>
                  </view>
                  <text class="cc-more-text">更多</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="footer">
      <!-- 主要操作按钮组 -->
      <view class="action-buttons">
        <view class="btn pass" style="color: #67c23a;" v-if="formData.checkpower" @click="check(1)">
          <up-icon name="checkmark-circle-fill" size="22" color="#67c23a"></up-icon>
          通过
        </view>

        <view class="btn reject" style="color: #f56c6c;" v-if="formData.checkpower" @click="check(0)">
          <up-icon name="close-circle-fill" size="22" color="#f56c6c"></up-icon>
          拒绝
        </view>

        <view class="btn urge" style="color: #1890ff; " v-if="formData.cancelpower" @click="urgentEvents">
          <uni-icons type="notification-filled" size="22" color="#1890ff"></uni-icons>
          催办
        </view>

        <view class="btn cancel" style="color: #ff4d4f;" v-if="formData.cancelpower" @click="cancelForm">
          <uni-icons type="undo" size="22" color="#ff4d4f"></uni-icons>
          撤销
        </view>

        <div class="btn commentA" style="color: #1e88e5;" @click="openCommentModal">
          <up-icon name="chat-fill" size="22" color="#1e88e5"></up-icon>
          评论
        </div>

        <div class="btn more" @click="openMoreOptions">
          <view>
            <up-icon name="more-dot-fill" size="20" color="#000" class="more-icon"></up-icon>
          </view>
          <view>
            <text class="more-text">更多</text>
          </view>
        </div>
      </view>

    </view>


    <!-- 审批人员查看更多 -->
    <up-popup mode="bottom" v-model:show="showPopup"
      :customStyle="{ padding: '0', backgroundColor: '#fff', borderRadius: '24rpx 24rpx 0 0' }">
      <view style="height: 70vh; display: flex; flex-direction: column;overflow: hidden;">
        <!-- 标题栏 -->
        <view class="popup-header">
          <text class="header-title">{{ showMorePeopleList.title }}</text>
          <view class="header-close" @click="closeMorePeople">
            <up-icon name="close" color="#999" size="20"></up-icon>
          </view>
        </view>

        <!-- 用户数量统计 -->
        <view class="user-count">
          共 {{ showMorePeopleList.content?.length || 0 }} 人
        </view>

        <!-- 用户列表 -->
        <scroll-view class="popup-content" scroll-y="true">
          <view class="user-list">
            <view class="user-item" v-for="(content, i) in showMorePeopleList.content" :key="'user_' + i"
              @click="viewUserInfo(content)">
              <view class="user-avatar">
                <image v-if="content.avatar" :src="content.avatar" mode="aspectFill"></image>
                <text v-else class="avatar-text">{{ content.name.charAt(0) }}</text>
              </view>
              <text class="user-name">{{ content.name }}</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </up-popup>

    <view style="height: 100rpx;"></view>

    <modalindex ref="modalindex" :modalTitle="modalTitle" :modalPlaceholder="modalPlaceholder"
      :Doyouwanttoinput="Doyouwanttoinput" @handleModalConfirm="handleModalConfirm"></modalindex>

    <!-- 更多弹窗 -->
    <moreOptionsPopup ref="moreOptionsPopup" :formData="formData" :nextCloud="nextCloud" :orderId="orderId"
      :userStore="userStore">
    </moreOptionsPopup>

    <!-- 评论弹窗 -->
    <commentPopup ref="commentPopup" :formData="formData" :nextCloud="nextCloud" :orderId="orderId"
      :userStore="userStore" :CommentName="CommentName" :commentText="commentText" :passonType="passonType"
      @getFormData="getFormData">
    </commentPopup>
  </view>
</template>

<script>

import modalindex from '@/components/Operationboxpublic/modalindex.vue'
import { COMMON_API_BASE_URL } from '@/utils/request'
import dayinimg from '../../../static/apply/dayin.png'
import { useUserStore } from '@/pinia-store/user'
import { mapStores } from 'pinia'
import apply from "@/apis/cloud/apply.js"
import OrgPicker from "@/components/OrgPicker/index.vue"
import QrCodePhotoUpload from '../form/components/QrCodePhotoUpload'
import { ProcessingURL, viewFile, getdownloadFileH5 } from '@/utils/publicmethod.js'
import { orderList, productList, products, customerList, orderCustomer } from './tableColumns.js'
import moreOptionsPopup from './components/moreOptionsPopup.vue'
import commentPopup from './components/commentPopup.vue'
export default {
  components: {
    OrgPicker,
    modalindex,
    QrCodePhotoUpload,
    moreOptionsPopup,
    commentPopup
  },
  data () {
    return {
      imgs: [],
      COMMON_API_BASE_URL,
      dayinimg,
      MoreOptionsPop: false,
      renyuanshow: false,
      title: '详情',
      orderId: '',
      formData: {}, // 用于存放数据的属性
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      topHeight: 0,
      listHeightStylePage: {},
      tableData: [{}], // 订单-客户信息
      isCommentModalVisible: false, // 控制弹窗显示
      commentText: '', // 评论内容
      customInputMentions: [],// 评论@的人员
      showPopup: false,
      showMorePeopleList: {}, // 查看人员
      uploadFilesList: [], // 上传的文件列表
      mentionCursorPosition: 0, // 记录@时光标位置
      atBlocks: [], //
      uploadimgList: [], // 图片列表
      modalTitle: '',
      modalPlaceholder: '',
      Doyouwanttoinput: false,
      modaltype: null,
      modalTitleGet: false,
      passonList: [],
      passonType: 1,
      CommentName: '发表评论',
      nextCloud: {},
      isSubmitting: false, // 新增：用于标记是否正在提交
      GetQrCodeList: [],
      orderList,
      productList,
      products,
      customerList,
      orderCustomer,
    }
  },
  computed: {
    ...mapStores(useUserStore)
  },
  watch: {
    modalTitleGet (value) {
      uni.setStorageSync('modalTitleGet', value)
    }
  },
  created () {
    this.nextCloud = uni.getStorageSync('next_cloud');
    let app = uni.getSystemInfoSync();
    this.topHeight = app.statusBarHeight;
    this.calculateListHeight()
    uni.$on('getFormData', () => {
      this.getFormData();
    })
  },
  onUnload () {
    uni.$emit('onUnloadupdateMileagePhoto')
    uni.$off('applyOrderDetail');
    uni.$off('getFormData');
    this.$refs.moreOptionsPopup.destroyClick()
    this.$refs.commentPopup.destroyClick()
  },
  methods: {
    ProcessingURL,
    hasScanPhoto (item) {
      if (!this.GetQrCodeList || !Array.isArray(this.GetQrCodeList)) return false;
      return this.GetQrCodeList.some(qr => qr.componentId === item.id && qr.isScanPhoto);
    },
    Withdrawalevent (id) {
      this.modaltype = id
      this.modalTitle = `确定撤回评论吗`
      this.Doyouwanttoinput = false
      this.$refs.modalindex.open('Withdrawalevent')
    },
    async WithdrawaleventClick () {
      uni.showLoading({
        title: '正在撤回评论中...'
      });
      let params = {
        id: this.modaltype,
      }
      const result = await apply.ApplycancelComment({
        ...params
      });

      uni.hideLoading();
      if (result.status > 0) {
        setTimeout(() => {
          uni.showToast({
            title: '撤回评论成功',
            icon: 'success',
          });
        }, 100);

        this.getFormData()
      }
      else {
        uni.showToast({
          title: '撤回评论失败',
          icon: 'error',
        });
      }
    },
    // 检查是否是图片
    isImage (filename) {
      if (!filename) return false;
      const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
      const extension = filename.split('.').pop().toLowerCase();
      return imageExtensions.includes(extension);
    },
    truncateMiddle (text, maxLength = 20) {
      if (text.length <= maxLength) return text;
      const half = Math.floor(maxLength / 2.5);
      return `${text.slice(0, half)}...${text.slice(-half)}`;
    },
    handleImageError (event, img) {
      // 设置图片加载失败标志
      this.$set(img, 'error', true);

      // 动态生成替代文字
      if (img.filename) {
        this.$set(img, 'altText', img.filename); // 使用文件名
      } else if (img.path) {
        const fileName = img.path.split('/').pop(); // 提取路径中的文件名
        this.$set(img, 'altText', fileName || '图片加载失败');
      } else {
        this.$set(img, 'altText', '图片加载失败'); // 默认提示文字
      }
    },
    openMoreOptions () {
      this.$refs.moreOptionsPopup.openMoreOptions()
      // this.MoreOptionsPop = true
    },
    // 关闭更多选项弹窗
    closeMoreOptions () {
      this.MoreOptionsPop = false;
    },
    // 获取所有在 commentText 中存在的 @名字
    getMentionNamesInText (text) {
      const matches = text.match(/@([\u4e00-\u9fa5A-Za-z0-9_]+)/g);
      return matches ? matches.map(item => item.substring(1)) : [];
    },
    showMorePeople (peopleList) {
      this.showMorePeopleList = peopleList
      this.showPopup = true
    },
    closeMorePeople () {
      this.showPopup = false
    },

    // 打开评论弹窗
    openCommentModal () {
      let data = {
        CommentName: '发表评论',
        passonType: 1,
        commentText: '',
        customInputMentions: [],
        uploadimgList: [],
        uploadFilesList: [],
        passonList: []
      }
      this.$refs.commentPopup.commentPopupClick(data)
    },
    // 打开@人员面板
    openAtPanel () {
      this.mentionCursorPosition = this.commentText.length;
      uni.navigateTo({
        url: '/components/OrgPicker/index?overlay=false&entry=component&VisibleandHidden=true&title=人员选择&type=user&multiple=false&source=applyOrderDetail'
      });
    },
    // 关闭评论弹窗
    closeCommentModal () {
      this.isCommentModalVisible = false;
      this.commentText = ''; // 清空输入框
      this.passonType = 1
    },

    calculateListHeight () {
      const windowHeight = window.innerHeight; // 视口高度
      // #ifdef APP-PLUS
      this.listHeightStyle = {
        overflowY: 'auto'
      };
      // #endif

      // #ifdef H5
      const listHeight = windowHeight
      this.listHeightStyle = {
        height: `${listHeight}px`,
        overflowY: 'auto'
      };
      // #endif
    },
    leftClick () {
      uni.navigateBack({
        delta: 1
      });
      if (this.modalTitleGet) {
        uni.$emit('refreshApplyList');
      }
    },
    closePopup () {
      this.renyuanshow = false
    },
    // 获取数据
    async getFormData () {
      console.log('触发了');

      // 显示加载框
      uni.showLoading({
        title: '加载中'
      });
      const result = await apply.getApplyDetail({
        id: this.orderId
      });
      if (result.status > 0) {
        this.formData = result.data;
        this.getapplyGetQrCodeComponents(this.orderId)
      } else {
        uni.showToast({
          title: '查看表单数据失败',
          icon: 'error'
        });
      }
      // 隐藏加载框
      uni.hideLoading();
    },
    getString (value) {
      var list = [];
      value.map(item => {
        list.push(item.value);
      })
      return list.join(',');
    },
    check (e) {
      this.modalTitle = `${e == 1 ? '审批通过' : '确认拒绝'}意见`
      this.modalPlaceholder = `请输入${e == 1 ? '通过' : '拒绝'}的具体原因 ${e == 0 ? '(必填)' : ''}`
      this.Doyouwanttoinput = true
      this.modaltype = e
      this.$refs.modalindex.open('check')
    },
    async handleModalConfirm (value) {
      if (value.source == 'check') { // 审批
        this.checkClick(value.value)
      } else if (value.source == 'cancelForm') { // 撤回表单
        this.cancelFormClick()
      } else if (value.source == 'Withdrawalevent') { // 撤回评论事件
        this.WithdrawaleventClick()
      } else if (value.source == 'urgentEvents') { // 催办事件
        this.urgentEventsClick()
      }
    },
    async checkClick (value) {
      uni.showLoading({
        title: `${this.modaltype == 1 ? '正在审批中...' : '正在驳回中...'}`
      });
      let params = {
        id: this.orderId,
        remark: value,
        type: this.modaltype,
      }

      const result = await apply.Applycheck({
        ...params
      });
      uni.hideLoading();
      if (result.status > 0) {
        setTimeout(() => {
          uni.showToast({
            title: `${this.modaltype == 1 ? '审批通过' : '驳回成功'}`,
            icon: 'success',
          });
        }, 100);

        this.getFormData()
        this.modalTitleGet = true
      } else {
        this.modalTitleGet = false
        uni.$u.toast(result.msg || `${this.modaltype == 1 ? '通过失败' : '驳回失败'}`);
      }
    },
    cancelForm () {
      this.modalTitle = '确定撤销吗？'
      this.Doyouwanttoinput = false
      this.$refs.modalindex.open('cancelForm')
    },
    async cancelFormClick () {
      uni.showLoading({
        title: '正在撤销中...'
      });
      let params = {
        id: this.orderId,
      }

      const result = await apply.Applycancel({
        ...params
      });
      uni.hideLoading();
      if (result.status > 0) {
        setTimeout(() => {
          uni.showToast({
            title: result.msg || '撤销成功',
            icon: 'success',
          });
        }, 100);
        this.getFormData()
        this.modalTitleGet = true
      } else {
        this.modalTitleGet = false
        uni.$u.toast(result.msg || '撤销失败');
      }
    },
    // 查看文件
    FileViewClick (data, item) {
      viewFile(item, {
        fileList: data, // 传入整组文件，实现图片多图预览
        userStore: this.userStore,
        xtoken: this.nextCloud?.xtoken,
      });
    },
    Relatedpopups (item) {
      uni.navigateTo({
        url: '/pages/apply/oaList/RelatedpopupsDetail?id=' + item.id
      });
    },
    ImgviewClick (item, img, val) {
      let imgList = [];
      let index = 0;

      // 确保图片的完整 URL
      img.url = ProcessingURL(img.url || img.path);

      if (val === 'pl') {
        item?.forEach((aitem) => {
          if (aitem?.url || aitem?.path) {
            const fullUrl = ProcessingURL(aitem.url || aitem.path);
            imgList.push(fullUrl);
          }
        });

        index = imgList.findIndex(url => url === img.url);
      } else {
        if (item?.value) {
          item.value.forEach((aitem) => {
            if (aitem?.url || aitem?.path) {
              const fullUrl = ProcessingURL(aitem.url || aitem.path);
              imgList.push(fullUrl);
            }
          });
        } else {
          item?.forEach((aitem) => {
            if (aitem?.url || aitem?.path) {
              const fullUrl = ProcessingURL(aitem.url || aitem.path);
              imgList.push(fullUrl);
            }
          });
        }

        // 确保比较的一致性
        const fullImgUrl = ProcessingURL(img.url || img.path);
        index = imgList.findIndex(url => url === fullImgUrl);
      }

      if (index === -1) index = 0;

      uni.previewImage({
        current: index,
        urls: imgList,
      });
    },

    urgentEvents () {
      this.modalTitle = '确定催办吗？'
      this.Doyouwanttoinput = false
      this.$refs.modalindex.open('urgentEvents')
    },
    async urgentEventsClick () {
      uni.showLoading({
        title: '正在催办中...'
      });
      let params = {
        id: this.orderId,
      }
      const result = await apply.ApplyUrge({
        ...params
      });

      uni.hideLoading();
      if (result.status > 0) {
        setTimeout(() => {
          uni.showToast({
            title: '催办成功',
            icon: 'success',
          });
        }, 100);

      }
      else {
        uni.showToast({
          title: '催办失败',
          icon: 'error',
        });
      }
    },
    viewUserInfo (value) {
      uni.navigateTo({
        url: '/pages/addressBook/details/grdetails',
        animationType: 'none',
        success: function (res) {
          res.eventChannel.emit('details', {
            item: {
              id: value.id,
              worker_name: value.name
            }
          })
        }
      });

    },
    async getapplyGetQrCodeComponents (id) {
      try {
        let res = await apply.applyGetQrCodeComponents({
          apply_id: this.orderId
        });

        if (res.status == 1) {
          this.GetQrCodeList = res.data
        }

      } catch (error) {

      }
    },
  },
  onLoad (option) { //option为object类型，会序列化上个页面传递的参数
    this.orderId = option.id; //赋值单据idg
    this.getFormData();
  }
}
</script>

<style lang="scss" scoped>
@import "./applyOrderDetail.scss";

.app {
  overflow-x: hidden;
  background-color: #F3F4F5;
  height: 100vh;
}
</style>
